#include "pagedquerywidget.h"
#include "filterwidget.h"
#include "tablemodel.h"
#include <QTableView>
#include <QPushButton>
#include <QLabel>
#include <QLineEdit>
#include <QComboBox>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QHeaderView>
#include <QApplication>
#include <QScreen>
#include <QIntValidator>
#include <QMessageBox>
#include <QDebug>

PagedQueryWidget::PagedQueryWidget(const QString &configPath, QWidget *parent)
    : QWidget(parent)
    , m_currentPage(1)
    , m_totalCount(0)
    , m_totalPages(0)
    , m_sortOrder(Qt::AscendingOrder)
{
    m_configManager = new ConfigManager(this);
    if (!m_configManager->loadConfig(configPath)) {
        QMessageBox::critical(this, "错误", "加载配置文件失败: " + configPath);
        return;
    }

    // 计算最佳页大小
    m_pageSize = calculateOptimalPageSize();

    initUI();
    initConnections();
}

void PagedQueryWidget::initUI()
{
    QVBoxLayout *mainLayout = new QVBoxLayout(this);

    // 创建筛选组件
    m_filterWidget = new FilterWidget(m_configManager->getFilters(), this);
    mainLayout->addWidget(m_filterWidget);

    // 创建表格组件
    m_tableView = new QTableView(this);
    m_tableModel = new TableModel(m_configManager->getColumns(), this);
    m_tableView->setModel(m_tableModel);

    // 配置表格外观
    m_tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    m_tableView->setAlternatingRowColors(true);
    m_tableView->setSortingEnabled(false); // 我们自己处理排序
    m_tableView->horizontalHeader()->setSectionsClickable(true);
    m_tableView->verticalHeader()->setVisible(false);

    // 设置列宽
    const QVector<ColumnConfig> &columns = m_configManager->getColumns();
    for (int i = 0; i < columns.size(); ++i) {
        m_tableView->setColumnWidth(i, columns[i].width);
    }

    // 使表格宽度自适应
    m_tableView->horizontalHeader()->setStretchLastSection(true);

    mainLayout->addWidget(m_tableView);

    // 创建分页控件
    QHBoxLayout *paginationLayout = new QHBoxLayout();

    m_totalLabel = new QLabel("总记录数: 0", this);
    m_firstPageBtn = new QPushButton("<<", this);
    m_prevPageBtn = new QPushButton("<", this);
    m_pageInfoLabel = new QLabel("第 0/0 页", this);
    m_nextPageBtn = new QPushButton(">", this);
    m_lastPageBtn = new QPushButton(">>", this);
    m_jumpPageEdit = new QLineEdit(this);
    m_jumpPageBtn = new QPushButton("跳转", this);
    m_pageSizeCombo = new QComboBox(this);

    // 配置分页控件
    m_jumpPageEdit->setFixedWidth(50);
    m_jumpPageEdit->setValidator(new QIntValidator(1, 9999, this));
    m_jumpPageEdit->setPlaceholderText("页码");

    // 设置页大小选项
    const PaginationConfig &paginationConfig = m_configManager->getPaginationConfig();
    for (int size : paginationConfig.pageSizeOptions) {
        m_pageSizeCombo->addItem(QString::number(size) + " 条/页", size);
    }

    // 设置当前页大小
    for (int i = 0; i < m_pageSizeCombo->count(); ++i) {
        if (m_pageSizeCombo->itemData(i).toInt() == m_pageSize) {
            m_pageSizeCombo->setCurrentIndex(i);
            break;
        }
    }

    // 添加分页控件到布局
    paginationLayout->addWidget(m_totalLabel);
    paginationLayout->addStretch();
    paginationLayout->addWidget(m_firstPageBtn);
    paginationLayout->addWidget(m_prevPageBtn);
    paginationLayout->addWidget(m_pageInfoLabel);
    paginationLayout->addWidget(m_nextPageBtn);
    paginationLayout->addWidget(m_lastPageBtn);
    paginationLayout->addStretch();
    paginationLayout->addWidget(m_jumpPageEdit);
    paginationLayout->addWidget(m_jumpPageBtn);
    paginationLayout->addWidget(m_pageSizeCombo);

    mainLayout->addLayout(paginationLayout);

    // 更新分页控件状态
    updatePaginationControls();

    setLayout(mainLayout);

    // 设置组件可调整大小
    loadStyleSheet();
    setMinimumSize(1100, 1100);
//    resize(800, 600);
}

void PagedQueryWidget::initConnections()
{
    // 筛选条件变化
    connect(m_filterWidget, &FilterWidget::filterChanged, this, &PagedQueryWidget::onFilterApplied);

    // 表头点击排序
    connect(m_tableView->horizontalHeader(), &QHeaderView::sectionClicked,
            this, &PagedQueryWidget::onHeaderClicked);

    // 表格单元格点击
    connect(m_tableView, &QTableView::clicked, this, &PagedQueryWidget::onTableClicked);

    // 分页控件事件
    connect(m_firstPageBtn, &QPushButton::clicked, this, &PagedQueryWidget::onFirstPage);
    connect(m_prevPageBtn, &QPushButton::clicked, this, &PagedQueryWidget::onPrevPage);
    connect(m_nextPageBtn, &QPushButton::clicked, this, &PagedQueryWidget::onNextPage);
    connect(m_lastPageBtn, &QPushButton::clicked, this, &PagedQueryWidget::onLastPage);
    connect(m_jumpPageBtn, &QPushButton::clicked, this, &PagedQueryWidget::onJumpToPage);
    connect(m_pageSizeCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &PagedQueryWidget::onPageSizeChanged);
    connect(m_jumpPageEdit, &QLineEdit::returnPressed, this, &PagedQueryWidget::onJumpToPage);
}

void PagedQueryWidget::setData(const QVector<QMap<QString, QVariant>> &data, int totalCount)
{
    m_totalCount = totalCount;
    m_tableModel->setData(data);

    // 如果有排序字段，应用排序
    if (!m_sortField.isEmpty()) {
        int sortColumnIndex = -1;
        const QVector<ColumnConfig> &columns = m_configManager->getColumns();
        for (int i = 0; i < columns.size(); ++i) {
            if (columns[i].field == m_sortField) {
                sortColumnIndex = i;
                break;
            }
        }

        if (sortColumnIndex >= 0) {
            m_tableModel->sort(sortColumnIndex, m_sortOrder);
        }
    }

    calculatePageInfo();
    updatePaginationControls();
}

QMap<QString, QVariant> PagedQueryWidget::getFilterValues() const
{
    return m_filterWidget->getFilterValues();
}

void PagedQueryWidget::calculatePageInfo()
{
    // 计算总页数
    m_totalPages = (m_totalCount + m_pageSize - 1) / m_pageSize;

    // 确保当前页在有效范围内
    if (m_currentPage < 1) {
        m_currentPage = 1;
    } else if (m_currentPage > m_totalPages && m_totalPages > 0) {
        m_currentPage = m_totalPages;
    }
}

void PagedQueryWidget::updatePaginationControls()
{

    //重置滚轮条到最顶端
    m_tableView->scrollToTop();

    // 更新总记录数标签
    m_totalLabel->setText(QString("总记录数: %1").arg(m_totalCount));

    // 更新页码信息
    m_pageInfoLabel->setText(QString("第 %1/%2 页").arg(m_currentPage).arg(m_totalPages == 0 ? 1 : m_totalPages));

    // 更新按钮状态
    m_firstPageBtn->setEnabled(m_currentPage > 1);
    m_prevPageBtn->setEnabled(m_currentPage > 1);
    m_nextPageBtn->setEnabled(m_currentPage < m_totalPages);
    m_lastPageBtn->setEnabled(m_currentPage < m_totalPages);
    m_jumpPageBtn->setEnabled(m_totalPages > 1);
    m_jumpPageEdit->setEnabled(m_totalPages > 1);
}

void PagedQueryWidget::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event); // 调用父类方法
       // 获取并输出当前窗口的分辨率
       QSize currentSize = this->size();
       qDebug() << "Window size changed - Width:" << currentSize.width()
                << "Height:" << currentSize.height();
}

int PagedQueryWidget::calculateOptimalPageSize()
{
    // 获取配置的默认页大小
    int defaultPageSize = m_configManager->getPaginationConfig().defaultPageSize;

    // 获取屏幕大小和DPI
    QScreen *screen = QApplication::primaryScreen();
    int screenHeight = screen->availableSize().height();

    // 估计每行高度（考虑到DPI）
    float dpiScale = screen->logicalDotsPerInch() / 96.0;
    int rowHeight = qRound(24 * dpiScale); // 基础行高24像素

    // 计算可视区域高度（考虑筛选区域和分页控件的高度）
    int filterHeight = qRound(150 * dpiScale); // 估计筛选区域高度
    int paginationHeight = qRound(50 * dpiScale); // 估计分页控件高度
    int tableHeaderHeight = qRound(30 * dpiScale); // 估计表头高度

    int availableHeight = screenHeight - filterHeight - paginationHeight - tableHeaderHeight;

    // 计算最佳行数
    int optimalRows = availableHeight / rowHeight;

    // 确保至少显示5行，最多显示默认页大小的行数
    optimalRows = qMax(5, qMin(optimalRows, defaultPageSize));

    return optimalRows;
}

void PagedQueryWidget::onFilterApplied()
{
    // 重置到第一页
    m_currentPage = 1;

    // 获取筛选条件
    QMap<QString, QVariant> filters = m_filterWidget->getFilterValues();

    // 发送筛选变化信号
    emit filterChanged(filters);
}

void PagedQueryWidget::onHeaderClicked(int section)
{
    const QVector<ColumnConfig> &columns = m_configManager->getColumns();

       // 检查列是否可排序
       if (section < 0 || section >= columns.size() || !columns[section].sortable) {
           return;
       }

       QString field = columns[section].field;

       // 如果点击的是当前排序列，切换排序顺序
       if (field == m_sortField) {
           m_sortOrder = (m_sortOrder == Qt::AscendingOrder) ? Qt::DescendingOrder : Qt::AscendingOrder;
       } else {
           m_sortField = field;
           m_sortOrder = Qt::AscendingOrder;
       }

       // 应用排序到当前显示的数据
       m_tableModel->sort(section, m_sortOrder);

       // 发送排序变化信号
       emit sortChanged(m_sortField, m_sortOrder);
}

void PagedQueryWidget::onTableClicked(const QModelIndex &index)
{
    if (!index.isValid()) {
        return;
    }

    // 检查列是否可交互
    if (!m_tableModel->isColumnInteractive(index.column())) {
        return;
    }

    int row = index.row();
    int column = index.column();
    QString field = m_tableModel->getFieldName(column);
    QVariant value = index.data();

    // 发送单元格点击信号
    emit cellClicked(row, column, field, value);
}

void PagedQueryWidget::onPageSizeChanged(int index)
{
    int newPageSize = m_pageSizeCombo->itemData(index).toInt();

    if (newPageSize != m_pageSize) {
        // 计算新的当前页，尽量保持相同的起始记录
        int startRecord = (m_currentPage - 1) * m_pageSize + 1;
        m_pageSize = newPageSize;
        m_currentPage = (startRecord + m_pageSize - 1) / m_pageSize;

        calculatePageInfo();
        emit pageChanged(m_currentPage, m_pageSize);
    }
}

void PagedQueryWidget::onFirstPage()
{
    if (m_currentPage > 1) {
        m_currentPage = 1;
        updatePaginationControls();
        emit pageChanged(m_currentPage, m_pageSize);
    }
}

void PagedQueryWidget::onPrevPage()
{
    if (m_currentPage > 1) {
        m_currentPage--;
        updatePaginationControls();
        emit pageChanged(m_currentPage, m_pageSize);
    }
}

void PagedQueryWidget::onNextPage()
{
    if (m_currentPage < m_totalPages) {
        m_currentPage++;
        updatePaginationControls();
        emit pageChanged(m_currentPage, m_pageSize);
    }
}

void PagedQueryWidget::onLastPage()
{
    if (m_currentPage < m_totalPages) {
        m_currentPage = m_totalPages;
        updatePaginationControls();
        emit pageChanged(m_currentPage, m_pageSize);
    }
}

void PagedQueryWidget::onJumpToPage()
{
    QString pageText = m_jumpPageEdit->text().trimmed();
    if (pageText.isEmpty()) {
        return;
    }

    bool ok;
    int page = pageText.toInt(&ok);

    if (ok && page >= 1 && page <= m_totalPages && page != m_currentPage) {
        m_currentPage = page;
        updatePaginationControls();
        emit pageChanged(m_currentPage, m_pageSize);
    }

    m_jumpPageEdit->clear();
}

void PagedQueryWidget::loadStyleSheet()
{
    // 从资源文件加载样式表
      QFile file(":/styles.qss");
      if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
          QString styleSheet = QLatin1String(file.readAll());
          setStyleSheet(styleSheet);
          file.close();
      } else {
          qWarning() << "Failed to load style sheet from resources";
      }
}
